import 'dart:async';

import 'package:star_author/config/app.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/controller/app_package_info_getx_controller.dart';
import 'package:star_author/env/env_config.dart';
import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/user_login_event.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/utils/rouces_util.dart';

import 'package:star_author/utils/user_util.dart';
import 'package:star_author/utils/websocket_manage/websocket_manage.dart';
import 'package:star_author/views/anchor/home_page_new_ui.dart';
import 'package:star_author/views/anchor/user_info_page.dart';
import 'package:star_author/views/login/phone_login.dart';
import 'package:dio_log/http_log_list_widget.dart';
import 'package:draggable_widget/draggable_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';

import '../../utils/http/api_manager.dart';
import '../../utils/http/http_util.dart';
import '../../utils/rong_im/rong_im.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late StreamSubscription loginStatusSubscription;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initConfigProviderData();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      if (UserUtil.isLogin(Get.context!)) {
        initUser();
      } else {
        Get.to(PhoneLoginPage());
      }
      // if (!EnvConfig.isProd()) {
      //   WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      //     _insertOverlay(context);
      //   });
      // }
    });
    loginStatusSubscription =
        GlobalEventBus().bus.on<UserLoginEvent>().listen((event) {
      if (event.isLogin) {
        initUser();
        setState(() {});
      }
    });
  }

  void _insertOverlay(BuildContext context) {
    return Overlay.of(context)?.insert(
      OverlayEntry(builder: (context) {
        final size = MediaQuery.of(context).size;
        return DraggableWidget(
          bottomMargin: 60,
          topMargin: 60,
          intialVisibility: true,
          horizontalSpace: 20,
          shadowBorderRadius: 20,
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Get.to(HttpLogListWidget());
            },
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.1),
                borderRadius: BorderRadius.circular(100),
              ),
              width: 36,
              height: 36,
              child: Text(
                "http",
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
            ),
          ),
          initialPosition: AnchoringPosition.bottomLeft,
        );
      }),
    );
  }

  initUser() {
    HttpUtil.commonRequest(
      Get.context!,
      ApiManager.current_tiny,
      isLoading: false,
      isErrorToast: false,
      queryParameters: {
        "scene": "happ-${Get.currentRoute}",
      },
    ).then((value) {
      Provider.of<UserProvider>(context, listen: false)
          .set(key: 'userInfo', value: value.data);
      WebSocketManage().initWebSocket();
      setState(() {});
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    loginStatusSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: [
        NewUiHomePage(),
        UserInfoPage(),
      ][currentIndex],
      bottomNavigationBar: SafeArea(
        child: Container(
          height: 49.w,
          color: Colors.white,
          width: Get.width,
          child: Row(
            children: List.generate(
              bottoms.length,
              (index) => Expanded(
                child: buildIcon(
                    bottoms[index]['title'], bottoms[index]['icon'], index),
              ),
            ),
          ),
        ),
      ),
    );
  }

  int currentIndex = 0;

  List bottoms = [
    {
      "title": "首页",
      "icon": "ic_index_lt",
      "select_icon": "ic_index_a_lt",
    },
    {
      "title": "个人中心",
      "icon": "ic_index_anchor_lt",
      "select_icon": "ic_index_anchor_a_lt",
    },
  ];

  buildIcon(String text, icon, index) {
    Color color = currentIndex == index ? Colors.black : Color(0xFF969798);
    icon = currentIndex == index ? bottoms[index]['select_icon'] : icon;
    return GestureDetector(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            RoucesUtil.getAssets(icon),
            width: 28.w,
            height: 28.w,
          ),
          SizedBox(
            height: 2.w,
          ),
          Text(
            text,
            style: TextStyle(
              color: color,
              fontSize: 10.sp,
              fontWeight:
                  currentIndex == index ? FontWeight.w600 : FontWeight.w400,
            ),
          )
        ],
      ),
      onTap: () {
        currentIndex = index;
        setState(() {});
      },
    );
  }

  void initConfigProviderData() async {
    PackageInfo? packageInfo =
        Get.find<AppPackageInfoGetXController>().packageInfo;
    String localVersion = packageInfo?.version ?? "";
    dynamic settingsRes = await HttpUtil.commonRequest(
      Get.context!,
      ApiManager.settings,
      queryParameters: {
        "app_version": localVersion,
      },
      isLoading: false,
      isErrorToast: false,
    );
    if (settingsRes.data != null) {
      IndexPageHandler.setAppConfig(settingsRes.data);

      ///融云聊天室
      await RongUtil.init();
    }
    if (UserUtil.isLogin(context)) {

    }
  }
}

class IndexPageHandler {
  static void setAppConfig(Map data) {
    Provider.of<ConfigProvider>(Get.context!, listen: false)
        .set(key: "settings", value: data);

    RongUtil.AppKey = data['rong_cloud_app_key'] ?? "y745wfm8y5e2v";
    App.appTitle = data["app_homepage_title"] ?? "闲置玉翠交易平台";
    App.shipped_time_description = data["shipped_time_description"] ?? "";
    App.gold_deducting_price = (double.parse(
        data["gold_deducting_price_for_classify"]['gold_ornament'].toString()));
    App.gold_deducting_price_for_classify =
        data["gold_deducting_price_for_classify"] ?? App.defaultClassify;
    App.wechat_gold_service_url = data["wechat_gold_service_url"] ?? "";
    App.popover_wait_time = data["popover_wait_time"] ?? 3;
    App.seconds_for_copy_clipboard = data["seconds_for_copy_clipboard"] ?? 60;
    App.wechat_appraise_service_url = data["wechat_appraise_service_url"] ?? "";
    StreamConf.PullBaseUrl =
        data['pull_base_url'] ?? StreamConf.PullBaseUrlDefault;
    StreamConf.PushBaseUrl =
        data['push_base_url'] ?? StreamConf.PushBaseUrlDefault;
    App.customerServiceUrl = data['wechat_service_url'] ??
        "https://work.weixin.qq.com/kfid/kfcfbc1ace60b3fa7b9";
    App.complaintsServiceUrl = data['wechat_complain_url'] ??
        "https://work.weixin.qq.com/kfid/kfc40ba31340078782d";

    App.universalLink = data['wechat_app_login_url'] ?? App.universalLink;
  }
}
